package com.sunny.common;

/**
 * @ClassName:
 * @Description:
 * @author: yubao.jin
 * @date: 2018/5/13
 * @version:V1.0
 */
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by JinDaShuai on 2018/1/24.
 */
public class TokenCache {
    public static Logger logger = LoggerFactory.getLogger(TokenCache.class);
    public static final String TOKEN_PREFIX = "token_";

    // 调用链的模式
    // initialCapacity(1000).maximumSize(100000)：设置缓存的初始化容量和最大容量
    // LRU算法；当超过这个容量的时候就采用LLU算法来移除缓存项
    // expireAfterAccess(12, TimeUnit.HOURS)：设置有效期为12小时
    public static LoadingCache<String, String> localCache = CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(100000).expireAfterAccess(12, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {
                // 默认的数据加载实现，当调用get取值的时候，如果key没有对应的值，就会调用此方法进行加载
                @Override
                public String load(String s) throws Exception {
                    return "null"; // 避免token在使用.equals时出现空指针异常
                }
            });

    public static void setKey(String key, String value) {
        localCache.put(key, value);
    }

    public static String getKey(String key) {
        String value = null;
        try{
            value = localCache.get(key);
            if("null".equals(value)) {
                return null;
            }
            return value;
        } catch (Exception e) {
            logger.error("localCache get error", e);
        }

        return null;
    }

}
